/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PantallaCalendarioEventos.java
 *
 * Created on 12-may-2011, 0:36:11
 */

package edu.uoc.tds.cliente;

import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Vector;

import javax.swing.JOptionPane;

import edu.uoc.tds.bean.CentroDocente;
import edu.uoc.tds.bean.Evento;
import edu.uoc.tds.bean.Universidad;
import edu.uoc.tds.common.EGestioEventsException;
import edu.uoc.tds.common.MostrarCombo;
import edu.uoc.tds.common.RemotoInterface;
import edu.uoc.tds.common.UtilLenguaje;
import edu.uoc.tds.common.Utils;
import edu.uoc.tds.common.Variables;

/**
 *
 * @author Alejandro Navarro
 */
public class PantallaCalendarioEventos extends javax.swing.JPanel {
	private static final long serialVersionUID = 5997341535338778227L;
	private RemotoInterface objServeis;

    /** Creates new form PantallaCalendarioEventos */
    public PantallaCalendarioEventos(RemotoInterface objServeis) throws RemoteException {
        super();
        this.objServeis = objServeis;

        initComponents();
        cargarCombos();
    }

    private void cargarCombos() throws RemoteException {
        Vector<MostrarCombo> listaUniversidades = objServeis.listaUniversidades();
        comboUniversidad.setModel(new javax.swing.DefaultComboBoxModel(listaUniversidades));
        rellenarCentros(new Integer(listaUniversidades.get(0).getID()));
    }

    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        botonAsistentes = new javax.swing.JButton();
        botonBuscar = new javax.swing.JButton();
        botonModificar = new javax.swing.JButton();
        botonCancelar = new javax.swing.JButton();
        botonNuevo = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        checkEventosCelebrados = new javax.swing.JCheckBox();
        checkEventosCancelados = new javax.swing.JCheckBox();
        fechaFin = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        fechaInicio = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        comboCentro = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        comboUniversidad = new javax.swing.JComboBox();

        jLabel1.setText(UtilLenguaje.getMessage("pantCalendarioEventos.filtro.titulo"));
        jLabel1.setName("jLabel1"); // NOI18N

        botonAsistentes.setText(UtilLenguaje.getMessage("pantCalendarioEventos.boton.asistentes"));
        botonAsistentes.setName("jButton4"); // NOI18N
        botonAsistentes.setEnabled(false);
        botonAsistentes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jVerAsistentesEventosActionPerformed(evt);
            }
        });

        botonBuscar.setText(UtilLenguaje.getMessage("pantCalendarioEventos.boton.buscar"));
        botonBuscar.setName("jButton5"); // NOI18N
        botonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jBuscarEventosActionPerformed(evt);
            }
        });

        botonModificar.setText(UtilLenguaje.getMessage("pantCalendarioEventos.boton.modificar"));
        botonModificar.setName("jButton2"); // NOI18N
        botonModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jIrModificarEventosActionPerformed(evt);
            }
        });
        botonModificar.setEnabled(false);

        botonCancelar.setText(UtilLenguaje.getMessage("pantCalendarioEventos.boton.cancelar"));
        botonCancelar.setName("jButton3"); // NOI18N
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jCancelarEventoActionPerformed(evt);
            }
        });
        botonCancelar.setEnabled(false);

        botonNuevo.setText(UtilLenguaje.getMessage("pantCalendarioEventos.boton.nuevo"));
        botonNuevo.setName("jButton1"); // NOI18N
        botonNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jIrAltaEventosActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            null,
            new String [] {
                UtilLenguaje.getMessage("pantCalendarioEventos.head.fecha"),
                UtilLenguaje.getMessage("pantCalendarioEventos.head.evento"),
                UtilLenguaje.getMessage("pantCalendarioEventos.head.centro"),
                UtilLenguaje.getMessage("pantCalendarioEventos.head.duracion")
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jTable1.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
            	seleccionarEvento(e.getPoint());
            }
        });

        jScrollPane1.setViewportView(jTable1);

        checkEventosCelebrados.setText(UtilLenguaje.getMessage("pantCalendarioEventos.filtro.celebrados"));
        checkEventosCelebrados.setName("jCheckBox2"); // NOI18N

        checkEventosCancelados.setText(UtilLenguaje.getMessage("pantCalendarioEventos.filtro.cancelados"));
        checkEventosCancelados.setName("jCheckBox1"); // NOI18N

        fechaFin.setText("");
        fechaFin.setName("jTextField2"); // NOI18N

        jLabel5.setText(UtilLenguaje.getMessage("pantCalendarioEventos.filtro.fechafin"));
        jLabel5.setName("jLabel5"); // NOI18N

        fechaInicio.setText("");
        fechaInicio.setName("jTextField1"); // NOI18N

        jLabel4.setText(UtilLenguaje.getMessage("pantCalendarioEventos.filtro.fechaini"));
        jLabel4.setName("jLabel4"); // NOI18N

        comboCentro.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboCentro.setName("jComboBox2"); // NOI18N

        jLabel2.setText(UtilLenguaje.getMessage("pantCalendarioEventos.filtro.universidad"));
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(UtilLenguaje.getMessage("pantCalendarioEventos.filtro.centro"));
        jLabel3.setName("jLabel3"); // NOI18N

        comboUniversidad.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboUniversidad.setName("jComboBox1"); // NOI18N
        comboUniversidad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRellenarComboCentroActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 461, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(80, 80, 80)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(fechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(23, 23, 23)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(fechaFin, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(botonNuevo)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botonModificar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botonCancelar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botonAsistentes))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(checkEventosCancelados)
                                    .addGap(32, 32, 32)
                                    .addComponent(checkEventosCelebrados)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(botonBuscar))
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 413, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(71, 71, 71)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(comboCentro, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(comboUniversidad, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 309, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(comboUniversidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(comboCentro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(fechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(fechaFin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(checkEventosCancelados)
                    .addComponent(botonBuscar)
                    .addComponent(checkEventosCelebrados))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonNuevo)
                    .addComponent(botonModificar)
                    .addComponent(botonCancelar)
                    .addComponent(botonAsistentes))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jRellenarComboCentroActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            rellenarCentros(new Integer(((MostrarCombo) comboUniversidad.getSelectedItem()).getID()));
        } catch (RemoteException re) {
        	Utils.tratarRemoteException(re);
        }
    }

    private void rellenarCentros(Integer idUniversidad) throws RemoteException {
        Vector<MostrarCombo> listaCentrosUniversidad = objServeis.listaCentrosUniversidad(idUniversidad);
        comboCentro.setModel(new javax.swing.DefaultComboBoxModel(listaCentrosUniversidad));
    }

    private void jBuscarEventosActionPerformed(java.awt.event.ActionEvent evt) {
        try {
        	if (validarFormatoDatos()) {
        		Evento evento = obtenerEvento();
        		List<Object[]> listaEventos = objServeis.consultarEventos(evento, checkEventosCancelados.isSelected(), checkEventosCelebrados.isSelected());
        		Object[][] consultarEventos = new Object[listaEventos.size()][4];
        		listaEventosId = new Object[listaEventos.size()][2];
        		Object[] fila = null;
        		for (int i = 0; i < listaEventos.size(); i++) {
        			fila = listaEventos.get(i);
        			consultarEventos[i][0] = Utils.convertirFecha((java.util.Date) fila[0]);
        			consultarEventos[i][1] = fila[1];
        			consultarEventos[i][2] = fila[2];
        			consultarEventos[i][3] = fila[3];
        			listaEventosId[i][0] = fila[4];
        			listaEventosId[i][1] = fila[5];
        		}
        		jTable1.setModel(new javax.swing.table.DefaultTableModel(consultarEventos,
        				new String [] {
        					UtilLenguaje.getMessage("pantCalendarioEventos.head.fecha"),
        					UtilLenguaje.getMessage("pantCalendarioEventos.head.evento"),
        					UtilLenguaje.getMessage("pantCalendarioEventos.head.centro"),
        					UtilLenguaje.getMessage("pantCalendarioEventos.head.duracion")
        				}
        		));
            	botonModificar.setEnabled(false);
            	botonCancelar.setEnabled(false);
            	botonAsistentes.setEnabled(false);
            	idEventoSeleccionado = null;
            	if (listaEventos.size() == 0) {
                    JOptionPane.showMessageDialog(null, UtilLenguaje.getMessage("pantCalendarioEventos.buscar.sinresultado.desc"),
                    		UtilLenguaje.getMessage("pantCalendarioEventos.buscar.titulo"), JOptionPane.INFORMATION_MESSAGE);
            	}
        	}
        } catch (RemoteException re) {
        	Utils.tratarRemoteException(re);
        } catch (EGestioEventsException e) {
        	Utils.tratarEGestioEventsException(e);
        }
    }

    private Evento obtenerEvento() {
    	Evento evento = new Evento();

    	if (!Utils.isEmpty(fechaInicio.getText())) {
    		evento.setFechaInicio(Utils.convertirFecha(fechaInicio.getText()));
    	}
    	if (!Utils.isEmpty(fechaFin.getText())) {
    		evento.setFechaFin(Utils.convertirFecha(fechaFin.getText()));
    	}
    	Integer idCombo = null;
    	if (comboCentro.getSelectedItem() != null) {
    		idCombo = ((MostrarCombo) comboCentro.getSelectedItem()).getID();
        	if (idCombo.intValue() > 0) {
        		evento.setCentroDocente(new CentroDocente(idCombo));
        	}
    	}
    	idCombo = ((MostrarCombo) comboUniversidad.getSelectedItem()).getID();
    	evento.setUniversidad(new Universidad(idCombo));

    	return evento;
    }


    private boolean validarFormatoDatos() throws EGestioEventsException {
    	String campoFormato = null;

    	if (!Utils.isEmpty(fechaInicio.getText()) && !Utils.isDate(fechaInicio.getText())) {
    		campoFormato = "pantCalendarioEventos.err.fechaini.formato";
    	} else if (!Utils.isEmpty(fechaFin.getText()) && !Utils.isDate(fechaFin.getText())) {
    		campoFormato = "pantCalendarioEventos.err.fechafin.formato";
    	}

    	if (campoFormato != null) {
        	EGestioEventsException e = new EGestioEventsException();
    		e.setDescripcion(campoFormato);
    		e.setTitulo("pantCalendarioEventos.err.titulo.campos.formato");
    		throw e;
    	}

    	return true;
    }

    private void seleccionarEvento(Point p) {
        int fila = jTable1.rowAtPoint(p);
        Integer idCentro = (Integer) listaEventosId[fila][1];
        idEventoSeleccionado = null;
        if (Variables.usuarioConectado.getCentroDocente().getIdCentroDocente().intValue() == idCentro.intValue()) {
        	idEventoSeleccionado = (Integer) listaEventosId[fila][0];
        	botonModificar.setEnabled(true);
        	botonCancelar.setEnabled(true);
        	botonAsistentes.setEnabled(true);
        } else {
        	botonModificar.setEnabled(false);
        	botonCancelar.setEnabled(false);
        	botonAsistentes.setEnabled(false);
        }
    }

    private void jIrModificarEventosActionPerformed(java.awt.event.ActionEvent evt) {
    	PantallaGestionEventos pantallaGestionEventos = new PantallaGestionEventos(objServeis, Variables.MODIFICACION);
    	pantallaGestionEventos.rellenarEvento(idEventoSeleccionado);
    	this.getParent().add(pantallaGestionEventos);
    	this.setVisible(false);
    	pantallaGestionEventos.setVisible(true);
    }

    private void jIrAltaEventosActionPerformed(java.awt.event.ActionEvent evt) {
    	PantallaGestionEventos pantallaGestionEventos = new PantallaGestionEventos(objServeis, Variables.ALTA);
    	pantallaGestionEventos.setVisible(false);
    	this.getParent().add(pantallaGestionEventos);
    	this.setVisible(false);
    	pantallaGestionEventos.setVisible(true);
    }

    private void jVerAsistentesEventosActionPerformed(java.awt.event.ActionEvent evt) {
    	PantallaAsistentesEvento pantallaAsistentesEvento = new PantallaAsistentesEvento(objServeis, idEventoSeleccionado);
    	if (pantallaAsistentesEvento.existenAsistentes()) {
	    	pantallaAsistentesEvento.setVisible(false);
	    	this.getParent().add(pantallaAsistentesEvento);
	    	this.setVisible(false);
	    	pantallaAsistentesEvento.setVisible(true);
    	}
    }
    private void jCancelarEventoActionPerformed(java.awt.event.ActionEvent evt) {
    	try {
    		if (JOptionPane.showConfirmDialog(null, UtilLenguaje.getMessage("pantGestionEventos.pregunta.baja.desc"), 
    				UtilLenguaje.getMessage("pantGestionEventos.conf.baja.titulo"), JOptionPane.OK_CANCEL_OPTION) == 0) {
    			objServeis.eliminarEvento(idEventoSeleccionado);
    			JOptionPane.showMessageDialog(null, UtilLenguaje.getMessage("pantGestionEventos.conf.baja.desc"),
    					UtilLenguaje.getMessage("pantGestionEventos.conf.baja.titulo"), JOptionPane.INFORMATION_MESSAGE);
    			jBuscarEventosActionPerformed(evt);
    		}
		} catch (RemoteException re) {
			Utils.tratarRemoteException(re);
		}
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonNuevo;
    private javax.swing.JButton botonModificar;
    private javax.swing.JButton botonCancelar;
    private javax.swing.JButton botonAsistentes;
    private javax.swing.JButton botonBuscar;
    private javax.swing.JCheckBox checkEventosCancelados;
    private javax.swing.JCheckBox checkEventosCelebrados;
    private javax.swing.JComboBox comboUniversidad;
    private javax.swing.JComboBox comboCentro;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField fechaInicio;
    private javax.swing.JTextField fechaFin;
    private Object[][] listaEventosId = null;
    private Integer idEventoSeleccionado = null;
    // End of variables declaration//GEN-END:variables

}
